import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.filechooser.FileFilter;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.commons.io.*;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;


/**
 * Create the controls (getInfo and save)
 * @author jcoston
 *
 */
public class Controls extends JPanel implements ActionListener {

	private static final long serialVersionUID = 1L;
	private JButton export;
	private JButton getInfo;
	private JButton help;
	private FlowLayout layout;
	private CSVModel model;
	private Table table;
	private Tree tree;

	/**
	 * Initialize the buttons, layout, and listeners
	 * @param m
	 * @param tr
	 * @param ta
	 */
	public Controls(CSVModel m, Tree tr, Table ta) {
		table = ta;
		tree = tr;
		model = m;
		
		//Set layout...Change from flow? !*!*!*!*!*!*!*!*!*!
		layout = new FlowLayout();
		setLayout(layout);

		//Create the save button
		export = new JButton("Export to Excel");
		export.addActionListener(this);

		//Create the getInfo button
		getInfo = new JButton("Get Information");
		getInfo.addActionListener(this);
		
		//Create the help button
		help = new JButton("Help");
		help.addActionListener(this);
		
		add(export);
		add(getInfo);
		add(help);

	}

	/**
	 * Respond to the user clicking a button
	 * @param e
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		Object source = e.getSource();
		//Save/Export Button
		if (source == export) {
			File file;
			//Bring up file chooser
			JFileChooser fileChooser = new JFileChooser();
			fileChooser.setFileFilter(new TypeOfFile());
			int returnVal = fileChooser.showSaveDialog(this);
			if (returnVal == JFileChooser.APPROVE_OPTION) {
				file = fileChooser.getSelectedFile();
				//If file already exits, display message
				if (file.exists()) {
					returnVal = JOptionPane.showConfirmDialog(this,
							"The file exists. Replace?");
					if (returnVal == JOptionPane.NO_OPTION) {
						return;
					}
				}
				File name = new File(file + ".csv");
				model.write(name);
			}
		}
		
		if (source == getInfo) {
			System.out.println("You clicked update!");
			//get the the query info
			//walk JTree and create GSON Object
			String filters = tree.getJSONFilters();
			
			//send the info									
			sendRequest(filters);
		}
		if (source == help){
			System.out.println("You clicked help!");
			JFrame frame = new JFrame("Help");
	        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			JOptionPane.showMessageDialog(frame, "Help can be found in the links on the right");
		}
	}
	
	public void sendRequest(String filters){
		CSVModel model = table.getModel();
		String jsonString = "";

		try {
			//send filters and get back string
			DefaultHttpClient client = new DefaultHttpClient();
			HttpPost request = new HttpPost("http://localhost:80/reswell/query_fdb");
			
			request.addHeader("content-type","application/json");
			request.setEntity(new StringEntity(filters));
			HttpResponse response = client.execute(request);
			
			InputStreamReader inReader = new InputStreamReader(response.getEntity().getContent());
			BufferedReader bReader = new BufferedReader(inReader);
			String line;
			while ((line = bReader.readLine()) != null)
				jsonString += line;
			
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		
		// The String we get from the Response InputStream has the form  "set('[...]')"
		// I have no idea why... but here's a hack to fix it:
		jsonString = jsonString.substring(6, jsonString.length()-3);
		
		// ssshhh...
		
		
		String[][] rows = new Gson().fromJson(jsonString, new TypeToken<String[][]>(){}.getType());
		model.populate(tree.fieldArray.toArray(new String[tree.fieldArray.size()]), rows);

	}
	

	/**
	 * Create a file filter that only allows the user to save as a csv file
	 * @author jcoston
	 */
	class TypeOfFile extends FileFilter {
		
		/**
		 * Set the type of file that should be display in JFileChooser
		 * We choose to display only csv files
		 * @param f
		 */
		public boolean accept(File f) {
			return f.isDirectory()
					|| f.getName().toLowerCase().endsWith(".csv");
		}

		/**
		 * Set description for the type of file that should be displayed
		 */
		public String getDescription() {
			return "Comma Seperated Value (.csv)";
		}
	}

}
